#include <stdio.h>
#include <assert.h>
#include <string.h>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <stdlib.h>

#define MAX 1024
#define ARGC 64
#define SEP " "

int split(char *commandstr, char *argv[])
{
    assert(commandstr);
    assert(argv);

    argv[0] = strtok(commandstr, SEP);
    if (argv[0] == NULL)
        return -1;
    int i = 1;
    while (argv[i++] = strtok(NULL, SEP))
        ;
    // while (1)
    // {
    //     argv[i] = strtok(NULL, SEP);
    //     if (argv[i] == NULL)
    //         break;
    //     i++;
    // }
    return 0;
}

void debugPrint(char *argv[])
{
    int i = 0;
    for (i = 0; argv[i]; i++)
    {
        printf("%d : %s\n", i, argv[i]);
    }
}

int main()
{
    char commandstr[MAX] = {0};
    char *argv[ARGC] = {NULL};
    while (1)
    {
        printf("[zhangsan@mymachine currpath]#");
        fflush(stdout);
        char *s = fgets(commandstr, sizeof(commandstr), stdin);
        assert(s);
        (void)s;
        commandstr[strlen(commandstr) - 1] = '\0';

        int n = split(commandstr, argv);
        assert(n == 0);
        if (n != 0)
            continue;
        debugPrint(argv);

        pid_t id = fork();
        assert(id >= 0);
        (void)id;
        if (id == 0)
        {
            // child
            execvp(argv[0],argv);
            exit(1);
        }
        int status = 0;
        waitpid(id, &status, 0);
        // printf("%s\n",commandstr);
    }
    return 0;
}